<template>
  <el-dialog v-model="dialogShow" :title="dialog.title" width="800px" @close="handleCloseDialog()">
    <div v-loading="dialog.loading">
      <el-form ref="flowFormRef" :model="formData" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="任务名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入任务名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色" prop="activityRole">
              <el-select v-if="props.nodeType == FlowNodeType.AUDITOR_NODE" :disabled="formData.systemd"
                v-model="formData.activityRole" placeholder="请选择">
                <el-option v-for="role in Object.keys(FLOW_ACT_AUDITOR_ROLE_LABEL)" :key="role"
                  :label="FLOW_ACT_ROLE_LABEL[role]" :value="role" />
              </el-select>
              <el-select v-else :disabled="formData.systemd" v-model="formData.activityRole" placeholder="请选择">
                <el-option v-for="role in Object.keys(FLOW_ACT_BUSINESS_ROLE_LABEL)" :key="role"
                  :label="FLOW_ACT_ROLE_LABEL[role]" :value="role" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="候选类型" prop="candidateType">
              <el-select v-model="formData.candidateType" placeholder="请选择" @change="handleCandidateType">
                <el-option v-for="type in Object.keys(FLOW_CANDIDAT_TYPE_LABEL)" :key="type"
                  :label="FLOW_CANDIDAT_TYPE_LABEL[type]" :value="type" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formData.candidateType != FlowCandidatType.ASSIGN">
            <el-form-item label="候选人" prop="candidateId">
              <el-select v-model="formData.candidateId" placeholder="请选择">
                <el-option v-for="c in candidateOpts" :key="c.value" :label="c.label" :value="c.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审批人类型" prop="auditType">
              <el-select v-model="formData.auditType" placeholder="请选择" @change="handleAuditType">
                <el-option v-for="type in Object.keys(FLOW_CANDIDAT_TYPE_LABEL)" :key="type"
                  :label="FLOW_CANDIDAT_TYPE_LABEL[type]" :value="type" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formData.candidateType != FlowCandidatType.ASSIGN">
            <el-form-item label="审批候选人" prop="auditorId">
              <el-select v-model="formData.auditorId" placeholder="请选择">
                <el-option v-for="c in auditOpts" :key="c.value" :label="c.label" :value="c.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="任务描述" prop="remark">
              <el-input type="textarea" v-model="formData.remark" placeholder="请输入任务描述"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 属性列表 -->
      <el-button size="small" type="primary" @click="handleAdd()">+ 添加填报项</el-button>
      <el-table :data="formData.flowNodeTaskDataConfigs" stripe size="small" height="220" class="data-table__content">
        <el-table-column type="index" width="60" align="center" />
        <el-table-column label="填报项名称" prop="property">
          <template #default="scope">
            <el-input :disabled="scope.row.systemd" v-model="scope.row.property" size="small"
              placeholder="请输入填报项名称"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="数据类型" prop="dataType">
          <template #default="scope">
            <el-select :disabled="scope.row.systemd" v-model="scope.row.dataType" size="small" placeholder="请选择">
              <el-option v-for="item in Object.keys(FLOW_TASK_DATA_TYPE_LABEL)" :key="item"
                :label="FLOW_TASK_DATA_TYPE_LABEL[item]" :value="item" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="数据备选项" prop="options">
          <template #default="scope"></template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="170" align="center">
          <template #default="scope">
            <el-button :disabled="scope.row.systemd" size="small" type="danger" link @click="handleDelete(scope)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="handleCloseDialog()">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import FlowNodeTaskAPI, {
  FLOW_ACT_ROLE_LABEL,
  FLOW_ACT_AUDITOR_ROLE_LABEL,
  FLOW_ACT_BUSINESS_ROLE_LABEL,
  FLOW_CANDIDAT_TYPE_LABEL,
  FLOW_TASK_DATA_TYPE_LABEL,
  FlowActivityRole,
  FlowCandidatType,
  FlowNodeTaskDataConfig,
  FlowNodeTaskDetailVo,
} from "@/api/flow/flowNodeTask.api";
import { FlowNodeType } from "@/api/flow/flowNode.api";
import DeptAPI from "@/api/system/dept.api";
import RoleAPI from "@/api/system/role.api";
import UserAPI from "@/api/system/user.api";
import JobAPI from "@/api/system/job.api";
import { cloneDeep } from "lodash-es";

const props = defineProps<{
  visible: boolean;
  nodeId: string;
  nodeType?: string;
  flowId?: string;
  id?: string;
}>();
const emits = defineEmits<{
  (e: "dialogClose", isRefresh?: boolean): void;
}>();

const dialog = reactive({
  title: "",
  loading: false,
});
// 处理props的数据 重新定义 dialogVisible
const dialogShow = computed({
  get() {
    return props.visible;
  },
  set(val) {
    return val;
  },
});

const flowFormRef = ref();
const defaultForm: FlowNodeTaskDetailVo = {
  id: "",
  name: "",
  remark: "",
  flowId: "",
  flowNodeId: "",
  candidateId: "",
  candidateName: "",
  candidateType: "",
  candidateNum: 1,
  activityRole:
    props.nodeType == FlowNodeType.AUDITOR_NODE
      ? FlowActivityRole.AUDITOR
      : FlowActivityRole.ASSIGNEE,
  flowNodeTaskDataConfigs: [],
};
const defaultDataForm: FlowNodeTaskDataConfig = {
  id: "",
  dataType: "",
  property: "",
  val: "",
  options: "",
};

// 默认审批节点数据
const defaultAuditorDataFormArray: FlowNodeTaskDataConfig[] = [
  {
    id: "",
    dataType: "OPTION",
    property: "审核结果",
    val: "",
    options: "通过,拒绝",
    systemd: true,
  },
  {
    id: "",
    dataType: "TEXT",
    property: "理由",
    val: "",
    options: "",
    systemd: true,
  },
];

const rules = reactive({

  name: [{ required: true, message: "请输入任务名称", trigger: "blur" }],
  candidateType: [{ required: true, message: "请选择候选类型", trigger: "blur" }],
  candidateId: [{ required: true, message: "请选择候选人", trigger: "blur" }],

});
const formData = reactive<FlowNodeTaskDetailVo>(cloneDeep(defaultForm));

const userOpts = ref<OptionType[]>([]); //备选-用户
const dptOpts = ref<OptionType[]>([]); //备选-部门
const jobOpts = ref<OptionType[]>([]); //备选-岗位
const roleOpts = ref<OptionType[]>([]); //备选-角色
const candidateOpts = ref<OptionType[]>([]); //候选者备选
const auditOpts = ref<OptionType[]>([]); //审批人备选

watch(
  () => props.visible,
  (val) => {
    if (val) {
      dialog.title = props.id ? "修改任务" : "新增任务";
      loadFlowDetail();
    }
  },
  {
    immediate: true,
  }
);

/**
 * 加载详情
 */
const loadFlowDetail = () => {
  if (!props.id) {
    if (props.nodeType == FlowNodeType.AUDITOR_NODE) {
      formData.flowNodeTaskDataConfigs = defaultAuditorDataFormArray;
      formData.activityRole = FlowActivityRole.AUDITOR;
    } else {
      formData.flowNodeTaskDataConfigs = [cloneDeep(defaultDataForm)];
      formData.activityRole = FlowActivityRole.ASSIGNEE;
    }
    formData.systemd = false;
    return;
  }
  dialog.loading = true;
  FlowNodeTaskAPI.loadDetail(props.id)
    .then((data) => {
      Object.assign(formData, data);
      // 加载备选-候选者
      loadCandidates(formData.candidateType, candidateOpts);
      loadCandidates(formData.auditType || "", auditOpts);
    })
    .finally(() => {
      dialog.loading = false;
    });
};

// 添加任务
function handleAdd() {
  formData.flowNodeTaskDataConfigs.push(cloneDeep(defaultDataForm));
}

// 删除节点
function handleDelete(scope: any) {
  formData.flowNodeTaskDataConfigs.splice(formData.flowNodeTaskDataConfigs.indexOf(scope.row), 1);
}

/**
 * 切换候选类型
 */
async function handleCandidateType(val: string) {
  formData.candidateId = "";
  loadCandidates(val, candidateOpts);
}

async function handleAuditType(val: string) {
  formData.auditorId = "";
  loadCandidates(val, auditOpts);
}

// 加载候选人
async function loadCandidates(val: string, opts: Ref<OptionType[]>) {
  switch (val) {
    case FlowCandidatType.USER:
      // 人员备选
      if (userOpts.value.length == 0) {
        const res = await UserAPI.getOptions();
        userOpts.value = res.map((r) => ({ label: r.realName, value: r.id }));
      }
      // candidateOpts.value = userOpts.value;
      // auditOpts.value = userOpts.value;
      opts.value = userOpts.value;
      break;
    case FlowCandidatType.ROLE:
      // 角色备选
      if (roleOpts.value.length == 0) {
        const res = await RoleAPI.getOptions();
        roleOpts.value = res.map((r) => ({ label: r.name, value: r.id }));
      }
      // candidateOpts.value = roleOpts.value;
      // auditOpts.value = roleOpts.value;
      opts.value = roleOpts.value;
      break;
    case FlowCandidatType.DEP:
      // 部门备选
      if (dptOpts.value.length == 0) {
        const res = await DeptAPI.getOptions();
        dptOpts.value = res.map((r) => ({ label: r.name, value: r.id }));
      }
      // candidateOpts.value = dptOpts.value;
      // auditOpts.value = dptOpts.value;
      opts.value = dptOpts.value;
      break;
    case FlowCandidatType.JOB:
      // 岗位备选

      if (jobOpts.value.length == 0) {
        const res = await JobAPI.getOptions();
        jobOpts.value = res.map((r) => ({ label: r.name, value: r.id }));
      }
      opts.value = jobOpts.value;
      // candidateOpts.value = jobOpts.value;
      // auditOpts.value = jobOpts.value;
      break;
    default:
      // candidateOpts.value = [];
      // auditOpts.value = [];
      opts.value = [];
  }
}

/**
 * 提交表单
 */
const handleSubmit = () => {
  flowFormRef.value.validate((valid: boolean) => {
    if (valid) {
      dialog.loading = true;
      const candidates = formData.candidateId
        ? candidateOpts.value
          .filter((opt) => formData.candidateId == opt.value)
          .map((opt) => opt.label)
        : []; //候选人
      const audits = formData.auditorId
        ? auditOpts.value
          .filter((opt) => formData.auditorId == opt.value)
          .map((opt) => opt.label)
        : []; //审批人
      const sendData: FlowNodeTaskDetailVo = {
        ...formData,
        flowId: props.flowId,
        flowNodeId: props.nodeId,
        candidateName: candidates.join(","),
        auditorName: audits.join(","),
      };
      if (sendData.id) {
        FlowNodeTaskAPI.update(sendData)
          .then(() => {
            ElMessage.success("修改任务成功");
            handleCloseDialog(true);
          })
          .finally(() => (dialog.loading = false));
      } else {
        FlowNodeTaskAPI.create(sendData)
          .then((d) => {
            ElMessage.success("新增任务成功");
            handleCloseDialog(true);
          })
          .finally(() => (dialog.loading = false));
      }
    }
  });
};

/**
 * 关闭弹窗
 */
function handleCloseDialog(isRefresh?: boolean) {
  flowFormRef.value.resetFields();
  flowFormRef.value.clearValidate();
  Object.assign(formData, cloneDeep(defaultForm));
  emits("dialogClose", isRefresh);
}
</script>

<style lang="scss" scoped></style>
